﻿using DataImporter.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataImporter.Modules
{
    public partial class ucVA : UserControl
    {
        public ucVA()
        {
            InitializeComponent();
            this.cbbDropdown.SelectedIndex = 0;
        }

        private DBContext DBContext => new DBContext();

        private void ofdFile_FileOk(object sender, CancelEventArgs e)
        {
            var table = this.ofdFile.FileName.GetDataTable(this.cbbDropdown.SelectedItem.ToString().Replace("1", ""));
            switch (this.cbbDropdown.SelectedIndex)
            {
                case 0:
                    HandleFirst(table);
                    break;
                case 1:
                    HandleSecond(table);
                    break;
                case 2:
                    HandleThird(table);
                    break;
                case 3:
                    HandleFourth(table);
                    break;
                case 4:
                    HandleFive(table);
                    break;
                case 5:
                    HandleSix(table);
                    break;
            }
        }

        private void HandleFirst(DataTable table)
        {
            var risks = new List<LTHR>();
            foreach (DataRow row in table.Rows)
            {
                var product = row["产品"].ToString();
                if (product.IsNullOrEmpty())
                    continue;
                risks.Add(new LTHR
                {
                    Name = row["体检名称"].ToString(),
                    Category = row["分类"].ToString(),
                    Code = row["编码"].ToString(),
                    Id = int.Parse(row["ID"].ToString()),
                    Product = product,
                    ShortName = row["简称"].ToString(),
                    Unit = row["单位"].ToString(),
                    Order = int.Parse(row["顺序"].ToString())
                });
            }
            this.dgvData.DataSource = risks;
        }

        private void HandleSecond(DataTable table)
        {
            var risks = new List<LTHRReference>();
            foreach (DataRow row in table.Rows)
            {
                var standard = row["标准"].ToString();
                if (standard.IsNullOrEmpty())
                    continue;
                var rule = row["规则"].ToString().ConvertNull();
                if (!rule.IsNullOrEmpty())
                    try
                    {
                        DyncmicRuntime.Compute(rule, "男");
                        DyncmicRuntime.Compute(standard.Replace("v", "1"));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                risks.Add(new LTHRReference
                {
                    ExceptionExplain = row["描述"].ToString(),
                    RiskLevel = row["风险等级"].ToString(),
                    NLID = int.Parse(row["体检项目ID"].ToString()),
                    Code = row["编码"].ToString(),
                    Id = int.Parse(row["ID"].ToString()),
                    Standard = standard,
                    StandardStr = row["标准字符串"].ConvertNull(),
                    Rule = rule,
                    Score = int.Parse(row["分数"].ToString()),
                    Order = int.Parse(row["顺序"].ToString())
                });
            }
            this.dgvData.DataSource = risks;
        }

        private void HandleThird(DataTable table)
        {
            var risks = new List<VAQuestion>();
            foreach (DataRow row in table.Rows)
            {
                var name = row["问题"].ToString();
                if (name.IsNullOrEmpty())
                    continue;
                risks.Add(new VAQuestion
                {
                    Id = int.Parse(row["Id"].ToString()),
                    PEItems = row["子选项"].ToString(),
                    Name = name,
                    Radio = bool.Parse(row["是否为单选"].ToString()),
                    Required = bool.Parse(row["是否必选"].ToString()),
                    Value = row["分类名称"].ToString(),
                    Order = int.Parse(row["顺序"].ToString())
                });
            }
            this.dgvData.DataSource = risks;
        }

        private void HandleFourth(DataTable table)
        {
            var risks = new List<VAAnswer>();
            foreach (DataRow row in table.Rows)
            {
                var name = row["分类"].ToString();
                if (name.IsNullOrEmpty())
                    name = row["答案"].ToString();
                if (name.IsNullOrEmpty())
                    continue;
                var isVA = row["是心脑血管"].ToString();
                var rule = row["规则"].ToString();
                if (!rule.IsNullOrEmpty())
                    try
                    {
                        DyncmicRuntime.Compute(rule, "男");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        throw ex;
                    }
                risks.Add(new VAAnswer
                {
                    Id = int.Parse(row["Id"].ToString()),
                    Code = row["编码"].ToString(),
                    IsVA = isVA.IsNullOrEmpty() ? false : bool.Parse(isVA),
                    Name = name,
                    ParentID = int.Parse(row["父ID"].ToString()),
                    PE = row["体检项套餐编码"].ToString(),
                    Remark = row["描述"].ToString(),
                    Rule = rule,
                    Score = int.Parse(row["分数"].ToString()),
                    Order = int.Parse(row["顺序"].ToString())
                });
            }
            this.dgvData.DataSource = risks;
        }

        private void HandleFive(DataTable table)
        {
            var risks = new List<ReplenishPE>();
            var name = string.Empty;
            var PEItem = string.Empty;
            for (int i = 3; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                var low = row[3].ToString();
                name = row[0].IsNullOrEmptyDefaultValue(name);
                PEItem = row[1].IsNullOrEmptyDefaultValue(PEItem);
                if (low.IsNullOrEmpty())
                    continue;
                risks.Add(new ReplenishPE
                {
                    FilterSick = name,
                    CCHDLow = low,
                    CCHDHigh = row[5].ToString(),
                    CCHDMiddle = row[4].ToString(),
                    CISLow = row[6].ToString(),
                    CISMiddle = row[7].ToString(),
                    CISHigh = row[8].ToString(),
                    PEItem = PEItem,
                    ChildItem = row[2].ToString()
                });
            }
            this.dgvData.DataSource = risks;
        }

        private void HandleSix(DataTable table)
        {
            var lst = table.Rows.OfType<DataRow>().Select(c => new PhysicalExaminationItem
            {
                Name = c["项目名称"].ToString(),
                Code = c["项目编码"].ToString(),
                Description = c["临床意义"].ToString()
            }).Where(c => !c.Name.IsNullOrEmpty()).ToList();
            var codes = lst.Where(c => c.Code.IsNullOrEmpty()).ToList();
            var pes = DBContext.PhysicalExaminationItemDB.GetList();
            codes.ForEach(item =>
            {
                var c = pes.Find(d => d.Name == item.Name || d.Name.Contains(item.Name));
                item.Rule = c?.Description;
                item.Category = c?.Name;
                item.Code = c?.Code;
            });
            //if (codes.Count > 0)
            //{
            //    this.dgvData.DataSource = codes;
            //    MessageBox.Show("有空Code");
            //}
            var newItems = lst.Where(c => !pes.Any(d => d.Code == c.Code)).ToList();
            if (newItems.Count > 0)
            {
                this.dgvData.DataSource = newItems;
                MessageBox.Show("新增的");
            }
        }

        private void HandlePEPackage(DataTable table)
        {
            var pes = DBContext.PhysicalExaminationItemDB.GetList();
            var lst = new List<PhysicalExaminationItem>();
            foreach (DataRow row in table.Rows)
            {
                int.TryParse(row["顺序"].ToString(), out var order);
                int.TryParse(row["父ID"].ToString(), out var pid);
                float.TryParse(row["价格"].ToString(), out var price);

                var packName = row["组合套餐名称"].ToString().Trim();
                var packCode = row["组合套餐编码"].ToString().Trim();

                if (!packName.IsNullOrEmpty())
                {
                    lst.Add(new PhysicalExaminationItem
                    {
                    });
                }

                lst.Add(new PhysicalExaminationItem
                {
                    Category = row["分类"].ToString().Trim(),
                    Code = row["编码"].ToString().Trim(),
                    Description = row["临床意义"].ToString().Trim(),
                    Name = row["项目名称"].ToString().Trim(),
                    Order = order,
                    ParentID = pid,
                    Price = price,
                    Rule = row["规则"].ToString()
                });
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            this.ofdFile.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.cbbDropdown.SelectedIndex == 0)
            {
                //if (!DBContext.Db.DbMaintenance.IsAnyTable(nameof(GoutRisk)))
                //    DBContext.Db.CodeFirst.InitTables<GoutRisk>();
                DBContext.Db.DbMaintenance.TruncateTable<LTHR>();
                DBContext.LTHRDB.InsertRange((List<LTHR>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 1)
            {
                DBContext.Db.DbMaintenance.TruncateTable<LTHRReference>();
                DBContext.LTHRRenferenceDB.InsertRange((List<LTHRReference>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 2)
            {
                DBContext.Db.DbMaintenance.TruncateTable<VAQuestion>();
                DBContext.VAQuestionDB.InsertRange((List<VAQuestion>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 3)
            {
                DBContext.Db.DbMaintenance.TruncateTable<VAAnswer>();
                DBContext.VAAnswerDB.InsertRange((List<VAAnswer>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 4)
            {
                DBContext.Db.DbMaintenance.TruncateTable<ReplenishPE>();
                DBContext.ReplenishPEDB.InsertRange((List<ReplenishPE>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 5)
            {

            }
            MessageBox.Show("保存成功");
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var answers = DBContext.VAAnswerDB.GetList();
            var pes = DBContext.PhysicalExaminationItemDB.GetList();
            var table = new DataTable();
            table.Columns.AddRange(new DataColumn[] {
                new DataColumn{ ColumnName = "问题", DataType = typeof(string) },
                new DataColumn{ ColumnName = "组合套餐名称", DataType = typeof(string) },
                new DataColumn{ ColumnName = "组合套餐编码", DataType = typeof(string) },
                new DataColumn{ ColumnName = "项目名称", DataType = typeof(string) },
                new DataColumn{ ColumnName = "项目编码", DataType = typeof(string) },
                new DataColumn{ ColumnName = "价格", DataType = typeof(float) },
                new DataColumn{ ColumnName = "临床意义", DataType = typeof(string) },
                new DataColumn{ ColumnName = "规则", DataType = typeof(string) },
                new DataColumn{ ColumnName = "分类", DataType = typeof(string) },
                new DataColumn{ ColumnName = "父ID", DataType = typeof(int) },
                new DataColumn{ ColumnName = "顺序", DataType = typeof(int) },
            });
            var bases = pes.FindAll(c => c.Code.StartsWith("PSHBE-"));
            bases.ForEach(item =>
            {
                var children = pes.FindAll(c => c.ParentID == item.Id);
                children.ForEach(child =>
                {
                    table.Rows.Add("", item.Name, item.Code, child.Name, child.Code, child.Price, child.Description, child.Rule, child.Category, item.Id, child.Order);
                });
            });
            var eQs = new HashSet<string>();
            pes.FindAll(c => c.ParentID == 0).ForEach(item =>
            {
                if (item.Code.StartsWith("PSHBE-"))
                    return;
                //先找所有的问题
                var allQs = answers.FindAll(q => q.PE.Contains(item.Code + ",") || q.PE.EndsWith(item.Code));
                allQs.ForEach(c =>
                {
                    if (eQs.Add(c.Code))
                        table.Rows.Add(c.Name);
                });
                var children = pes.FindAll(c => c.ParentID == item.Id);
                children.ForEach(child =>
                {
                    table.Rows.Add("", item.Name, item.Code, child.Name, child.Code, child.Price, child.Description, child.Rule, child.Category, item.Id, child.Order);
                });
            });
            table.SaveToExcel(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "体检项目.xls"), 0, 1, 2);
        }
    }
}
